package tgc.edu.exam.web.controller;

import java.util.HashSet;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import tgc.edu.exam.custom.CommonController;
import tgc.edu.exam.entity.TeachingProgramme;
import tgc.edu.exam.service.TbClassService;
import tgc.edu.exam.service.TbCurriculumService;
import tgc.edu.exam.service.TeacherService;
import tgc.edu.exam.web.form.TeachingProgrammeForm;

@Controller
@RequestMapping(value="/teachingProgramme")
public class TeachingProgrammeController extends CommonController<TeachingProgramme, UUID, TeachingProgrammeForm> {
	@Autowired
	private TbClassService tcService;
	@Autowired
	private TbCurriculumService tclService;
	@Autowired
	private TeacherService tService;
	
	@Override
	public void edit(TeachingProgrammeForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		map.put("tbClass", tcService.findAll());
		map.put("tbCurriculum", tclService.findAll());
		map.put("teacher", tService.findAll());
		super.edit(form, map);
	}
	
	@Override
	public Specification<TeachingProgramme> buildSpec(TeachingProgrammeForm form) {
		Specification<TeachingProgramme> specification = new Specification<TeachingProgramme>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<TeachingProgramme> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(StringUtils.hasText(form.getTacherName())) {
					Predicate name = cb.like(root.get("teacher").get("name"), "%"+form.getTacherName()+"%");
					rules.add(name);
				}
				if(StringUtils.hasText(form.getTbClassName())) {
					Predicate difficultylevel = cb.like(root.get("tbClass").get("name"), "%"+form.getTbClassName()+"%");
					rules.add(difficultylevel);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;
	}
	
}
